import axios from 'axios';
import { uploadFileToOSS } from './api';

const API_BASE_URL = 'http://localhost:5000/api';

interface RegisterData {
  username: string;
  password: string;
  nickname?: string;
  avatar?: string;
}

interface LoginData {
  username: string;
  password: string;
}

interface User {
  id: string;
  username: string;
  nickname: string;
  avatar?: string;
  role?: string;
}

// 注册用户
export const register = async (data: RegisterData): Promise<User> => {
  try {
    const response = await axios.post(`${API_BASE_URL}/admin/register`, data);

    if (response.data.success) {
      // 存储用户信息到本地
      localStorage.setItem('user', JSON.stringify(response.data.user));
      return response.data.user;
    } else {
      throw new Error(response.data.message || '注册失败');
    }
  } catch (error) {
    console.error('注册失败:', error);
    throw error;
  }
};

// 用户登录
export const login = async (data: LoginData): Promise<User> => {
  try {
    const response = await axios.post(`${API_BASE_URL}/admin/login`, data);

    if (response.data.success) {
      // 存储用户信息到本地
      localStorage.setItem('user', JSON.stringify(response.data.user));
      return response.data.user;
    } else {
      throw new Error(response.data.message || '登录失败');
    }
  } catch (error) {
    console.error('登录失败:', error);
    throw error;
  }
};

// 退出登录
export const logout = async (): Promise<void> => {
  // 清除本地存储的用户信息
  localStorage.removeItem('user');
};

// 获取当前用户信息
export const getCurrentUser = async (): Promise<User | null> => {
  try {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
      return null;
    }

    const user = JSON.parse(userStr);
    // 如果需要，可以在这里验证用户token有效性，向后端请求最新信息

    return user;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

// 上传头像
export const uploadAvatar = async (file: File): Promise<string> => {
  try {
    // 复用阿里云OSS上传逻辑
    const result = await uploadFileToOSS(file);
    return result.url;
  } catch (error) {
    console.error('上传头像失败:', error);
    throw error;
  }
};

// 检查用户是否为管理员
export const isAdmin = async (): Promise<boolean> => {
  try {
    const user = await getCurrentUser();
    return user?.role === 'admin';
  } catch (error) {
    console.error('检查管理员权限失败:', error);
    return false;
  }
};

// 检查用户是否为审核员
export const isAuditor = async (): Promise<boolean> => {
  try {
    const user = await getCurrentUser();
    return user?.role === 'auditor';
  } catch (error) {
    console.error('检查审核员权限失败:', error);
    return false;
  }
};